<template>
  <view class="page-container">
    <HeaderBar
        title="订单详情"
        navBarBgc="transparent"
    ></HeaderBar>
    <view class="content-container">
      <view class="address-container flex items-center justify-between" @click="showTouristAddress = true">
        <view class="left-container flex-1 flex items-center">
          <i class="iconfont icon-a-jinrudituquandidingweiweizhi"></i>
          <view class="address-content ml20">
           {{receiverObj.consigneeAddress}} {{receiverObj.consigneeName}}-{{receiverObj.consigneePhone}}
          </view>
        </view>
        <wd-icon name="arrow-right" size="30px" color="#2b2b24"></wd-icon>
      </view>
      <view class="provider-name">
        {{merchantName}}
      </view>
      <view class="product-info-container flex items-start ">
        <image class="product-img" :src="productDetailObj.headImageUrl"></image>
        <view class="other-info-container">
          <view class="product-name">{{productDetailObj.name}}.</view>
          <view class="specification-container">
            类型规格：{{typeName}}/{{specsName}} <!--200g I 袋装-->
          </view>
          <view class="favorable-container flex items-center">
            <view
                v-for="(item,index) in favorableList"
                :key="index"
                class="favorable-item"
            >
              {{item}}
            </view>
          </view>
          <view class="price-container flex items-center">
            <view class="sale-price">
              实付￥
              <text>{{productPrice}}</text>
            </view>
<!--            <view class="market-price">
              优惠前￥124.00
            </view>-->
          </view>
        </view>
      </view>
      <view class="stepper-content-container flex items-center justify-between">
        <view class="left-container">
          购买数量
        </view>
        <view class="stepper-container flex items-center">
          <i class="iconfont icon-jian" @click="changeNumber('decrement')"></i>
          <text class="pl20 pr20">{{number}}</text>
          <i class="iconfont icon-jia1" @click="changeNumber('increment')"></i>
        </view>
      </view>
      <view class="explanation-container">
        <view class="explanation-item flex items-center justify-between">
          <text>配送方式</text>
          <text>快递</text>
        </view>
        <view class="explanation-item flex items-center justify-between">
          <text>快递费</text>
          <text>{{productDetailObj.discountLost ? "￥" + productDetailObj.discountLost : '包邮'}}</text>
        </view>
        <view class="explanation-item flex items-center justify-between">
          <text>优惠</text>
          <text>每满200减0</text>
        </view>
        <view class="explanation-item flex items-center justify-between">
          <text>合计</text>
          <text>￥{{computerTotalPrice}}</text>
        </view>
      </view>
      <view class="remark-container">
        <view class="title">订单备注</view>
        <wd-textarea
            v-model="remarkContent"
            placeholder="请填写评价"
            :maxlength="60"
            custom-class="custom-textarea-class"
        />
      </view>
      <view class="agreement-container flex items-center justify-center" >
        <span class="flex items-center" @click="isAgree = !isAgree">
           <radio
               :value="true"
               :checked="isAgree"
               color="#1b9c61"
               style="transform: scale(0.7)"
           />
          我同意
        </span>
        <text>《用户协议》</text>
        与
        <text>《隐私协议》</text>
      </view>
      <view class="bottom-safe-container"></view>
      <view class="btn-bottom-container">
        <view class="top-container flex ">
          <view class="price">￥ {{computerTotalPrice}}</view>
          <view class="right-container">
            <view class="price-detail-tip" @click="showDetails = !showDetails">
              <text>明细</text>
              <wd-icon name="arrow-down" size="22px" v-if="!showDetails"></wd-icon>
              <wd-icon name="arrow-up" size="22px" v-else></wd-icon>
            </view>
            <view class="btn" @click="handleCreateOrder">去支付</view>
          </view>
        </view>
        <view class="safe-content" :style="{height: safeInsert + 'px'}"></view>
      </view>
    </view>
    <!--  明细 -->
    <wd-popup v-model="showDetails" custom-style="border-radius:12rpx;" position="bottom">
      <view style="min-height: 40vh">
        <wd-status-tip image="content" tip="暂无选择产品" v-if="!number"/>
        <view class="detail-container  pd20" v-else>
          <view class="flex items-center justify-between">
            <view class="product-name fw800 fs16">
              超干手撕风干牛肉干超干手撕风干牛肉干
            </view>
            <view class="price-number fw800 fs16">
              ￥{{productPrice}} * {{number}}
            </view>
          </view>
        </view>
      </view>
    </wd-popup>
    <TouristAddress
        :showTouristAddress="showTouristAddress"
		:activeAddressId="receiverObj.id"
        :touristAddressList="touristAddressList"
        @closeTouristAddress="closeTouristAddress"
        @updateTouristAddress="updateTouristAddress"
    ></TouristAddress>
  </view>
</template>

<script setup>
  import {ref, computed} from "vue";
  import {onLoad} from "@dcloudio/uni-app";
  import HeaderBar from "@/components/HeaderBar/index.vue";
  import TouristAddress from "@/specialtySubPack/components/touristAddress/index.vue";
  import {createSpeciality, specialtyProductDetail, touristAddressListApi} from "@/api/specialty";
  import {toPay} from "@/api/common";


  const favorableList = ref(["每满200减20"]);
  const number = ref(1);
  const remarkContent = ref("");
  const isAgree = ref(false);
  const safeInsert = ref(0);
  const showDetails = ref(false);
  const showTouristAddress = ref(false);
  const touristAddressList = ref([]);
  const productId = ref();
  const productName = ref();
  const merchantName = ref('');
  const merchantId = ref();
  const productPrice = ref(0);
  const typeName = ref('');
  const specsName = ref('');
  const specsId = ref();
  const typeId = ref();
  const receiverObj = ref({
    consigneeName: "",
    consigneePhone: "",
    consigneeAddress: "",
  });
  const typeData = ref('')
  const productDetailObj = ref({
    shippingAmount: "",
    packageAmount: "",
    skuName: "",
    productImg: "",
    productName: "",
  });
  const orderType = ref(null);

  const computerTotalPrice = computed(() => {
    return (productPrice.value * number.value).toFixed(2);
  });


  const updateTouristAddress = () => {
    queryTouristAddressList();
  };
  const changeNumber = (type) => {
    if(!number.value) return;
    switch (type) {
      case "increment":
        number.value += 1;
        break;
      case "decrement":
        number.value -= 1;
        break;

    }
  };
  const handleCreateOrder = async() => {
    let tipContent = "";
    if (!isAgree.value) {
      tipContent = "请阅读并同意用户协议和饮隐私协议";
    } else if(!number.value) {
      tipContent = "购买最少数量不能低于1";
    } else if(!receiverObj.value.consigneeName) {
      tipContent = "请完善收货人信息";
    }
    if(tipContent) {
      uni.showToast({
        icon: "none",
        title: tipContent
      })
      return;
    }
    let {consigneeName, consigneePhone, consigneeAddress, id: addressId} = receiverObj.value;
    await createSpeciality({
	  productId: productId.value,
	  productName: productDetailObj.value.name,
	  specsId: specsId.value,
	  typeId: typeId.value,
	  merchantId: merchantId.value,
	  merchantName: merchantName.value,
	  quantity: number.value,
	  specsName: specsName.value,
	  typeName: typeName.value,
	  couponId: null,
	  discountId: null,
	  totalAmount: (productPrice.value * number.value).toFixed(2),
	  payAmount: (productPrice.value * number.value).toFixed(2),
	  contactName: consigneeName,
	  contactPhone: consigneePhone,
	  address: consigneeAddress,
	  addressId: addressId,
	  productImgUrl: productDetailObj.value.headImageUrl,
	  memo: remarkContent.value
    }).then(res => {
      console.log(res,'res');
      let { orderId, orderType: _orderType } = res.result;
      orderType.value = _orderType;
      handleToPay(orderId);
    });
  };
  const handleToPay = async (id) => {
    await toPay({type:"jsapi",id}).then(res => {
	  let { appId,nonceStr, packageValue,paySign,signType,timeStamp } = res.result;
	  uni.navigateTo({
	  		url:`/ticketSubPack/pages/PaymentOrder/index?totalPrice=${computerTotalPrice.value}&timeStamp=${timeStamp}&nonceStr=${nonceStr}&packageValue=${encodeURIComponent(packageValue)}&signType=${signType}&paySign=${encodeURIComponent(paySign)}&orderId=${id}`
	  });
    });
  };
  const handleText = () => {
    console.log("点击")
  };
  const closeTouristAddress = async (event) => {
	  if (event) {
		  let {activeAddress} = event;
		  if (activeAddress) {
		  	receiverObj.value = activeAddress;
		  } else {
		  	receiverObj.value = {};
		  }
	  }
    showTouristAddress.value = false;
  };
const queryTouristAddressList = async () => {
    await touristAddressListApi({}).then(res => {
      if(res && res.result.length > 0) {
        touristAddressList.value = res.result;
        const {province, city, district, address, name, tel, id} = res.result.find(item => item.isDefault === 1) || res.result[0];
        receiverObj.value = {
          consigneeAddress: province + city + district + address,
          consigneeName: name,
          consigneePhone: tel,
		  id: id,
        };
      }
    });
  };
  const querySpecialtyProductDetail = async () => {
    await specialtyProductDetail({productId:productId.value}).then(res => {
      productDetailObj.value = res.result;
    });
  };

  onShow(() => {
    queryTouristAddressList();
  });
  onLoad((options) => {
    let {productPrice: _productPrice, specsId: _specsId, typeId: _typeId, productId: _productId, merchantId: _merchantId, productName: _productName, merchantName: _merchantName, typeName: _typeName, specsName: _specsName} = options;
    productPrice.value = _productPrice;
    productId.value = parseInt(_productId);
	merchantId.value = parseInt(_merchantId);
	productName.value = _productName;
    merchantName.value = _merchantName;
	specsName.value = _specsName;
	typeName.value = _typeName;
	typeId.value = parseInt(_typeId);
	specsId.value = parseInt( _specsId);
    safeInsert.value = uni.getSystemInfoSync().safeAreaInsets.bottom;
    querySpecialtyProductDetail();
  });

</script>

<style lang="scss" scoped>
  .page-container {
    min-height: 100vh;
    background: linear-gradient(180deg, rgba(184,207,192,1) 0%, rgba(233,240,235,.5) 14%, rgba(255,255,255,1) 100%);
    .content-container {
      padding: 30rpx 27.5rpx 0 27.5rpx;
      .address-container {
        padding: 20rpx 27rpx;
        border-radius: 10rpx;
        background-color: #DDDDDD;
        .left-container {
          margin-right: 82rpx;
          .icon-a-jinrudituquandidingweiweizhi {
            font-size: 60rpx;
          }
          .address-content {
            font-size: 33rpx;
            color: #2B2B24;
          }
        }
      }
      .provider-name {
        padding: 91.5rpx 0 28rpx 0;
        font-size: 29rpx;
        font-weight: bold;
      }
      .provider-name:after {
        display: block;
        content: "";
        width: 264.5rpx;
        height: 7rpx;
        margin-top: 2rpx;
        background: linear-gradient(90deg, rgba(27,156,97,1) 0%, rgba(143,206,178,1) 47%, rgba(235,246,241,1) 100%);
      }
      .product-info-container {
        .product-img {
          width: 250rpx;
          height: 166.5rpx;
          border-radius: 10rpx;
        }
        .other-info-container {
          padding-left: 30rpx;
          width: calc(100% - 250rpx);
          .product-name {
            height: 50rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 33.5rpx;
            font-weight: bold;
          }
          .specification-container {
            margin: 15rpx 0 11rpx 0;
            font-size: 25rpx;
          }
          .favorable-container {
            .favorable-item {
              padding: 2rpx 4rpx;
              font-size: 22rpx;
              border-radius: 7rpx;
              border: 1rpx solid #D33700;
              color: #D33700;
            }
          }
          .price-container {
            margin-top: 31.5rpx;
            .sale-price {
              font-size: 22rpx;
              color: #AA5413;
              padding-right: 15rpx;
              text {
                font-size: 33rpx;
                font-weight: bold;
                color: #AA5413;
              }
            }
            .market-price {
              padding-left: 15rpx;
              font-size: 25rpx;
              border-left: 1rpx solid #AA5413;
              color: #AA5413;
            }
          }
        }
      }
      .stepper-content-container {
        padding: 45rpx 0 21.5rpx 0;
        border-bottom: 1rpx solid #C0C2B3;
        .left-container {
          font-size: 29rpx;
          font-weight: bold;
        }
        .stepper-container {
          padding: 13rpx 16rpx;
          border-radius: 10rpx;
          background-color: #EEEFE7;
          .iconfont {
            color: #3d3d37;
            font-size:50rpx;
          }
        }
      }
      .explanation-container {
        padding: 53.5rpx 0 28.5rpx 0;
        font-size: 29rpx;
        font-weight: bold;
        .explanation-item {
          margin-bottom: 20rpx;
        }
      }
      .remark-container {
        padding: 29rpx 26.5rpx;
        border-radius: 10rpx;
        border: 1rpx solid #C0C2B3;
        .title {
          margin-bottom: 25rpx;
          font-size: 29rpx;
          font-weight: bold;
        }
        :deep(.custom-textarea-class) {
          padding: 0;
          .wd-textarea__value {
            height: 130rpx;
            overflow: hidden;
          }
        }
      }
      .agreement-container {
        margin-top: 15rpx;
        font-size: 25rpx;
        text {
          color: #AA5413;
        }
      }
      .bottom-safe-container {
        height: 200rpx;
      }
      .btn-bottom-container {
        position: fixed;
        width: 100%;
        bottom: 0;
        left: 0;
        z-index: 9;
        background: #fdffeb;
        .top-container {
          justify-content: space-between;
          align-items: center;
          padding: 32rpx 20rpx 0 59rpx;
          .price {
            font-size: 42rpx;
            font-weight: bold;
            color: #AA5413;
          }
          .right-container {
            display: flex;
            align-items: center;
            .price-detail-tip {
              display: flex;
              align-items: center;
              padding-right: 11rpx;
              text {
                font-size: 30rpx;
              }
            }
            .btn {
              border-radius: 10.5rpx;
              font-weight: bold;
              padding: 25rpx 32rpx;
              color: #FDFFEB;
              background: #AA5413;
            }
          }
        }
      }
    }
    .detail-container {
      .product-name {
        width: 65%;
        height: 50rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .price-number {
        color: #AA5413;
      }
    }
  }
</style>
